package com.dstz.agilebpm.sys.autoconfiguration.queue;

import cn.hutool.extra.mail.MailAccount;
import com.dstz.agilebpm.sys.autoconfiguration.cache.AbCacheType;
import com.dstz.sys.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

/**
 * 缓存相关配置
 *
 * @author jeff
 * @date 2018-8-12 22:36:19
 */
@Configuration
@Import(AbMessageQueueAutoConfiguration.AbCacheConfigurationSelector.class)
@EnableConfigurationProperties({MQMailConfigProperties.class, AbSimpleMessageQueueProperties.class})
public class AbMessageQueueAutoConfiguration {

    @Autowired
    private MQMailConfigProperties mqMailConfigProperties;

    public static class AbCacheConfigurationSelector implements ImportSelector {
        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            AbMessageQueueType[] types = AbMessageQueueType.values();
            String[] imports = new String[types.length];
            for (int i = 0; i < types.length; i++) {
                imports[i] = types[i].getConfigurationClass().getName();
            }
            return imports;
        }
    }

    @Component
    class MailAccountAutoConfiguration implements ApplicationListener<ContextRefreshedEvent> {

        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            if (event.getApplicationContext().getParent() == null) {
                setEmailConfiguration();
            }
        }
    }

    private void setEmailConfiguration() {
        MailAccount account = new MailAccount();
        account.setHost(mqMailConfigProperties.getSendHost());
        account.setPort(mqMailConfigProperties.getSendPort());
        account.setFrom(mqMailConfigProperties.getMailAddress());
        account.setUser(mqMailConfigProperties.getNickName());
        account.setPass(mqMailConfigProperties.getPassword());
        account.setSslEnable(mqMailConfigProperties.isSSL());
        EmailUtil.setAccount(account);
    }

}
